import { BaseRoute } from './BaseRoute.js';
import { ProductService } from '../service/ProductService.js';

export class ProductRoutes extends BaseRoute {
    constructor() {
        const productService = new ProductService();
        super(productService);
        this.productService = productService;
        this._setupRoutes();
    }

    _setupRoutes() {
        // 获取所有产品
        this.router.get('/', this.asyncHandler(async (req, res) => {
            const { page = 1, limit = 10, category, minPrice, maxPrice, search } = req.query;
            const filters = {
                page: parseInt(page),
                limit: parseInt(limit),
                category,
                minPrice: minPrice ? parseFloat(minPrice) : undefined,
                maxPrice: maxPrice ? parseFloat(maxPrice) : undefined,
                search
            };
            
            const result = await this.productService.getAllProducts(filters);
            
            this.success(res, {
                products: result.products,
                pagination: {
                    page: result.page,
                    limit: result.limit,
                    total: result.total,
                    totalPages: result.totalPages
                },
                filters: {
                    category: result.category,
                    priceRange: result.priceRange
                }
            });
        }));

        // 获取产品分类 (必须在 /:id 路由之前定义)
        this.router.get('/categories/list', this.asyncHandler(async (req, res) => {
            const categories = await this.productService.getCategories();
            this.success(res, categories);
        }));

        // 批量更新产品库存 (必须在 /:id 路由之前定义)
        this.router.patch('/inventory/batch', this.asyncHandler(async (req, res) => {
            const { updates } = req.body; // [{ id, stock }]
            
            if (!Array.isArray(updates) || updates.length === 0) {
                return this.error(res, 'Updates array is required', 400);
            }
            
            const result = await this.productService.batchUpdateInventory(updates);
            this.success(res, result, 'Inventory updated successfully');
        }));

        // 根据ID获取产品
        this.router.get('/:id', this.asyncHandler(async (req, res) => {
            const { id } = req.params;
            const product = await this.productService.getProductById(id);
            
            if (!product) {
                return this.error(res, 'Product not found', 404);
            }
            
            this.success(res, product);
        }));

        // 创建新产品
        this.router.post('/', this.asyncHandler(async (req, res) => {
            const productData = req.body;
            const newProduct = await this.productService.createProduct(productData);
            this.success(res, newProduct, 'Product created successfully', 201);
        }));

        // 更新产品
        this.router.put('/:id', this.asyncHandler(async (req, res) => {
            const { id } = req.params;
            const updateData = req.body;
            
            const updatedProduct = await this.productService.updateProduct(id, updateData);
            
            if (!updatedProduct) {
                return this.error(res, 'Product not found', 404);
            }
            
            this.success(res, updatedProduct, 'Product updated successfully');
        }));

        // 删除产品
        this.router.delete('/:id', this.asyncHandler(async (req, res) => {
            const { id } = req.params;
            const deleted = await this.productService.deleteProduct(id);
            
            if (!deleted) {
                return this.error(res, 'Product not found', 404);
            }
            
            this.success(res, null, 'Product deleted successfully');
        }));

        // 更新产品库存
        this.router.patch('/:id/stock', this.asyncHandler(async (req, res) => {
            const { id } = req.params;
            const stockData = req.body;
            const updatedProduct = await this.productService.updateStock(id, stockData);
            this.success(res, updatedProduct, 'Stock updated successfully');
        }));

        // 更新产品价格
        this.router.patch('/:id/price', this.asyncHandler(async (req, res) => {
            const { id } = req.params;
            const priceData = req.body;
            const updatedProduct = await this.productService.updatePrice(id, priceData);
            this.success(res, updatedProduct, 'Price updated successfully');
        }));
    }

}

// 创建并导出路由实例
const productRoutes = new ProductRoutes();
export default productRoutes.getRouter();